<template>
  <!-- 全货物列表 -->
  <div>
    <div class="btn-box" v-if="showBtn">
      <span class="btn_left">
        <el-button type="text" @click="addNewData('')">
          同步发货通知单货物信息
        </el-button>
        <!-- <el-button type="text" @click="deleteData">删除</el-button> -->
      </span>
    </div>

    <div class="statistical-information">
      <span class="statistical-title">总件数：</span>
      <span class="statistical-number">{{ calculateSum.pkgsSum }}</span>
      <span class="statistical-title">总毛重：</span>
      <span class="statistical-number">{{ calculateSum.weightSum }}</span>
      <span class="statistical-title">总体积：</span>
      <span class="statistical-number">{{ calculateSum.volumSum }}</span>
    </div>

    <el-form
      :model="tableData"
      label-width="0"
      label-suffix="："
      ref="tableFormRef"
      :show-message="false"
      v-loading="tableLoading"
      :rules="cargoTableDataRules"
    >
      <el-table
        :data="tableData.cargoTableData"
        stripe
        border
        height="100%"
        size="small"
        @cell-click="cellClick"
        :row-style="selectRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="40"
          v-if="showBtn"
        />
        <el-table-column align="center" type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column
          align="center"
          label="中文品名"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-form-item
                :prop="'cargoTableData.' + scope.$index + '.cargoChName'"
                :rules="cargoTableDataRules.cargoChName"
                v-if="scope.$index >= 0"
              >
                <el-input
                  v-model="scope.row.cargoChName"
                  size="small"
                  placeholder="请输入"
                  :ref="'cargoTableData' + scope.$index + scope.column.no"
                  @blur="ctnNoBlur(scope.$index, scope.column.no, scope.row)"
                  filterable
                >
                </el-input>
              </el-form-item>
            </div> -->
            <span>
              {{ scope.row.cargoChName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="英文品名"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.cargoName"
                size="small"
                placeholder="请输入"
                filterable
                @blur="modifySaveInTable(scope.row)"
              >
              </el-input>
            </div> -->
            <span>
              {{ scope.row.cargoName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="HS CODE"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-autocomplete
                v-model="scope.row.hscode"
                :fetch-suggestions="queryContainCode"
                placeholder="请输入选择"
                style="width: 100%"
                value-key="label"
                :clearable="true"
                @blur="modifySaveInTable(scope.row)"
                @select="cotainerCodeSelect"
              ></el-autocomplete>
            </div> -->
            <span>
              {{ scope.row.hscode }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="计划件数"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.pkgs"
                style="width: 100%"
                placeholder="请输入"
                clearable
                @input="scope.row.pkgs = validateNumber(scope.row.pkgs)"
                @blur="modifySaveInTable(scope.row)"
              />
            </div> -->
            <span>
              {{ scope.row.pkgs }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="未装件数"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.pkgs"
                style="width: 100%"
                placeholder="请输入"
                clearable
                @input="scope.row.pkgs = validateNumber(scope.row.pkgs)"
                @blur="modifySaveInTable(scope.row)"
              />
            </div> -->
            <span>
              {{ scope.row.pkgs }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="包装单位"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <selectDown
                v-model:modelData="scope.row.packageType"
                placeholder="请选择"
                urlType="CsPackageType"
                :fit-input-width="false"
                :autoWidth="true"
                @blur="modifySaveInTable(scope.row)"
              >
              </selectDown>
            </div> -->
            <span>
              {{ scope.row.packageType }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="重量(KGS)" show-overflow-tooltip>
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.grossWeight"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                @input="
                  scope.row.grossWeight = validateOnlyNumberTwo(
                    scope.row.grossWeight
                  )
                "
                clearable
              />
            </div> -->
            <span>
              {{ scope.row.grossWeight }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="体积(CBM)" show-overflow-tooltip>
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.measurement"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                @input="
                  scope.row.measurement = validateOnlyNumberTwo(
                    scope.row.measurement
                  )
                "
                clearable
              />
            </div> -->
            <span>
              {{ scope.row.measurement }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="唛头" show-overflow-tooltip>
          <template #default="scope">
            <!-- <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.marks"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                clearable
              />
            </div> -->
            <span>
              {{ scope.row.marks }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          align="center"
          label="UN Code(危)"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.unCode"
                style="width: 100%"
                @blur="modifySaveInTable(scope.row)"
                placeholder="请输入"
                clearable
              />
            </div>
            <span v-else>
              {{ scope.row.unCode }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="类别(危)"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.cargoClass"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                clearable
              />
            </div>
            <span v-else>
              {{ scope.row.cargoClass }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="联系电话(危)"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.telephone"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                @change="
                  scope.row.telephone = validataPhoneAndTelephone(
                    scope.row.telephone
                  )
                "
                clearable
              />
            </div>
            <span v-else>
              {{ scope.row.telephone }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="联系人(危)"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div
              v-if="
                scope.$index === rowIndex && scope.column.no === columnIndex
              "
            >
              <el-input
                v-model="scope.row.contacts"
                style="width: 100%"
                placeholder="请输入"
                @blur="modifySaveInTable(scope.row)"
                clearable
              />
            </div>
            <span v-else>
              {{ scope.row.contacts }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="addNewData(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-dialog
      :title="dialogData.title"
      v-model="dialogData.show"
      width="900px"
      @close="closeDailog"
    >
      <el-form
        v-if="showBtn"
        :model="formData"
        :rules="formRules"
        label-width="85px"
        label-suffix="："
        ref="formRef"
        :show-message="false"
      >
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="中文品名" prop="cargoChName">
              <el-input
                v-model="formData.cargoChName"
                type="textarea"
                :rows="2"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文品名">
              <el-input
                v-model="formData.cargoName"
                type="textarea"
                :rows="2"
                fit-input-width
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="HS CODE">
              <el-autocomplete
                v-model="formData.hscode"
                :fetch-suggestions="queryContainCode"
                placeholder="请输入选择"
                style="width: 100%"
                value-key="label"
                :clearable="true"
                @select="cotainerCodeSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="件数">
              <el-input
                v-model="formData.pkgs"
                style="width: 100%"
                placeholder="请输入"
                @input="formData.pkgs = validateNumber(formData.pkgs)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装单位">
              <selectDown
                v-model:modelData="formData.packageType"
                placeholder="请选择包装单位"
                urlType="CsPackageType"
                :fit-input-width="false"
                :autoWidth="true"
              >
              </selectDown>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="毛重">
              <el-input
                v-model="formData.grossWeight"
                placeholder="请输入"
                @input="
                  formData.grossWeight = validateOnlyNumberTwo(
                    formData.grossWeight
                  )
                "
              >
                <template #append>KGS</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积">
              <el-input
                v-model="formData.measurement"
                placeholder="请输入"
                @input="
                  formData.measurement = validateOnlyNumberTwo(
                    formData.measurement
                  )
                "
              >
                <template #append>CBM</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="唛头">
              <el-input
                v-model="formData.marks"
                type="textarea"
                :rows="3"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="UN Code(危)">
              <el-input v-model="formData.unCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别(危)">
              <el-input v-model="formData.cargoClass" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="联系电话(危)">
              <el-input
                v-model="formData.telephone"
                placeholder="请输入"
                @change="
                  formData.telephone = validataPhoneAndTelephone(
                    formData.telephone
                  )
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="formData.contacts" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="container-table" v-else>
        <div class="item item-layout item-min-height" style="width: 50%">
          <div class="label-item">中文品名</div>
          <div class="content-item">{{ formData.cargoChName }}</div>
        </div>
        <div class="item item-layout item-min-height" style="width: 50%">
          <div class="label-item">英文品名</div>
          <div class="content-item">
            {{ formData.cargoName }}
          </div>
        </div>
        <div class="item item-layout" style="width: 50%">
          <div class="label-item">HS CODE</div>
          <div class="content-item">
            {{ formData.hscode }}
          </div>
        </div>
        <div class="item item-layout" style="width: 25%">
          <div class="label-item">件数</div>
          <div class="content-item">
            {{ formData.pkgs }}
          </div>
        </div>
        <div class="item item-layout" style="width: 25%">
          <div class="label-item">包装单位</div>
          <div class="content-item">
            {{ formData.packageType }}
          </div>
        </div>
        <div class="item item-layout" style="width: 50%">
          <div class="label-item">毛重</div>
          <div class="content-item">{{ formData.grossWeight }}</div>
        </div>
        <div class="item item-layout" style="width: 50%">
          <div class="label-item">体积</div>
          <div class="content-item">
            {{ formData.measurement }}
          </div>
        </div>
        <div class="item item-layout" style="width: 100%">
          <div class="label-item">唛头</div>
          <div class="content-item">
            {{ formData.marks }}
          </div>
        </div>
      </div>
      <template #footer v-if="showBtn">
        <span class="dialog-footer">
          <el-button @click="cancel" type="default" size="small"
            >取消</el-button
          >
          <el-button type="primary" size="small" @click="submit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, toRaw } from 'vue'
import selectDown from './selectDownNew.vue'
import {
  validateOnlyNumberTwo,
  validateNumber,
  validataPhoneAndTelephone
} from '@/utils/validate.js'
export default defineComponent({
  components: {
    selectDown
  },
  props: {
    //详细数据
    detailData: {
      type: Object,
      default: () => {}
    },
    //详细数据
    showBtn: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:detailData'],
  computed: {
    data: {
      get() {
        return this.detailData
      },
      set(value) {
        this.$emit('update:detailData', value)
      }
    }
  },
  data() {
    return {
      tableData: {
        cargoTableData: []
      },
      tableLoading: false,
      rowIndex: -1, //行索引
      columnIndex: -1, //列索引
      tableSelect: [],
      dialogData: {
        title: '货物信息',
        show: false
      },
      calculateSum: {
        pkgsSum: 0,
        weightSum: 0,
        volumSum: 0
      },
      cargoTableDataRules: {
        cargoChName: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      formRules: {
        cargoChName: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      // 用于autocompelte组件
      timeout: null,
      formData: {
        id: 0,
        hscode: '', //HS CODE
        cargoName: '', //英文品名
        cargoChName: '', //中文品名
        marks: '', //唛头
        grossWeight: '', //毛重
        containerCode: '', //箱型
        containerTareWeight: '', //箱皮重
        pkgs: 0, //件数
        packageType: '', //包装单位
        unCode: '', //UN Code(危)
        cargoClass: '', //类别(危)
        grossWeight: '', //毛重
        telephone: '', //联系电话(危
        contacts: '', //联系人
        measurement: '' //体积
      }
    }
  },
  methods: {
    validateNumber,
    validataPhoneAndTelephone,
    validateOnlyNumberTwo,
    // HS-code查询
    queryContainCode(val, cb) {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.timeout = setTimeout(async () => {
        let res = await this.$http.get('/api/cshscode/querypage', {
          PageIndex: 1,
          PageSize: 50,
          KeyWords: val
        })
        if (res) {
          console.log(res, 'res')
          let options = res.content.map((item) => {
            return {
              id: item.id,
              value: item.cmCode,
              label: item.cmCode,
              selectLabel: item.cmCode
            }
          })
          cb(options)
        } else {
          console.error(error)
          cb([])
        }
      }, 200)
    },
    // hs-code选择
    cotainerCodeSelect(val) {
      console.log(val, 'val')
    },

    // 获取货物列表数据
    async getCargoTableList() {
      this.tableLoading = true
      let res = await this.$http.get('/api/secargo/query', {
        BookingId: this.$route.query.id
      })
      this.tableData.cargoTableData = res.content
      this.calculateSumAll(this.tableData.cargoTableData)
      this.tableLoading = false
    },

    // 中文品名输入
    ctnNoBlur(rowIndex, columnIndex, row) {
      this.$refs.tableFormRef.validate((value) => {
        if (value) {
          this.modifySaveInTable(row)
        }
      })
    },

    // 高亮勾选行
    selectRowClassName({ row, rowIndex }) {
      if (this.tableSelect.includes(row)) {
        return {
          'background-color': '#5A9CF819'
        }
      }
      return ''
    },

    // 设置当前表所有操作验证必填项是否填写
    async validateBoxes() {
      let falg = true
      await this.$refs.tableFormRef.validate((res) => {
        falg = res
      })
      if (!falg) {
        this.$message.error('请输入中文品名')
      }
      return falg
    },

    //单元格被点击时会触发该事件
    async cellClick(row, column, cell, event) {
      if (column.label != '操作' && column.no != 0) {
        let falg = await this.validateBoxes()
        if (falg) {
          this.rowIndex = this.tableData.cargoTableData.findIndex(
            (t) => t == row
          )
          this.columnIndex = column.no
        }
      }
    },
    /**
     * 选择后的数据
     */
    handleSelectionChange(val) {
      let arr = []
      for (let item of val) {
        let ret = toRaw(item)
        if (ret !== undefined) {
          arr.push(ret)
        }
      }
      this.tableSelect = arr
    },

    // 关闭dailog
    // closeDailog() {
    //   this.$refs.formRef.resetFields()
    // },
    // 新增
    async addNewData(row) {
      await this.$refs.tableFormRef.validate()
      this.formData = row
      if (!row) {
        this.formData = {
          bookingId: this.$route.query.id,
          id: 0,
          hscode: '', //HS CODE
          cargoName: '', //英文品名
          cargoChName: '', //中文品名
          marks: '', //唛头
          grossWeight: '', //毛重
          containerCode: '', //箱型
          containerTareWeight: '', //箱皮重
          pkgs: 0, //件数
          packageType: '', //包装单位
          unCode: '', //UN Code(危)
          cargoClass: '', //类别(危)
          grossWeight: '', //毛重
          telephone: '', //联系电话(危
          contacts: '', //联系人
          measurement: '' //体积
        }
      }
      this.dialogData.show = true
    },
    // 计算总件数和总毛重和总体积
    calculateSumAll(data) {
      this.calculateSum = {
        pkgsSum: 0,
        weightSum: 0,
        volumSum: 0
      }
      for (const iterator of data) {
        this.calculateSum.pkgsSum += iterator.pkgs ? parseInt(iterator.pkgs) : 0
        this.calculateSum.weightSum += iterator.grossWeight
          ? parseInt(iterator.grossWeight)
          : 0
        this.calculateSum.volumSum += iterator.measurement
          ? parseInt(iterator.measurement)
          : 0
      }
    },
    // 取消
    cancel() {
      this.dialogData.show = false
    },
    // 列表修改保存
    async modifySaveInTable(row) {
      let api = '/api/secargo/update'
      let res = await this.$http.post(api, row)
      if (res.status) {
        this.$message.success('成功')
        this.rowIndex = -1
        this.columnIndex = -1
        this.getCargoTableList()
      } else {
        this.$message.warning(res.message)
      }
    },
    // 保存
    async submit() {
      console.log(this.$refs.formRef, 'formRef')
      await this.$refs.formRef.validate()
      let api = '/api/secargo/create'
      if (this.formData.id) {
        api = '/api/secargo/update'
      }
      let res = await this.$http.post(api, this.formData)
      if (res.status) {
        this.$message.success('成功')
        this.dialogData.show = false
        this.getCargoTableList()
      } else {
        this.$message.warning(res.message)
      }
    },
    // 删除
    async deleteData() {
      if (this.tableSelect.length > 0) {
        let idArray = []
        for (const iterator of this.tableSelect) {
          idArray.push(iterator.id)
        }
        let res = await this.$http.post('/api/secargo/delete', {
          idArray: idArray
        })
        if (res.status) {
          this.$message.success('成功')
          this.getCargoTableList()
        } else {
          this.$message.warning(res.message)
        }
      } else {
        this.$message.error('请先选择')
      }
    }
  },
  watch: {}
})
</script>

<style lang="scss" scoped>
@import '@/styles/business/business.scss';
:deep(.el-table--border .el-table__inner-wrapper) {
  height: 280px;
}
:deep(.el-table) {
  .el-table__header th {
    background-color: #f7f8fa;
  }
  .cell {
    height: 28px;
    line-height: 28px;
  }
  .el-table_1_column_1 .cell {
    display: flex;
    align-items: center;
    height: 100%;
  }
  .el-table__cell {
    padding: 0;
    height: 28px;
  }
  .el-input-number {
    width: 100%;
    .el-input__inner {
      text-align: left;
      padding: 0 8px;
    }
    .el-input-number__decrease {
      display: none;
    }
    .el-input-number__increase {
      display: none;
    }
  }
  .el-input__inner {
    padding: 0 8px;
  }
  .el-date-editor {
    .el-input__prefix {
      display: none;
    }
  }
}

:deep(.el-dialog) {
  padding: 0px;
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 8px 16px;
  }

  .el-dialog {
    padding: 0px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
    text-align: center;
  }

  .el-form-item__label {
    padding: 0px;
    color: #000000d8;
    font-family: PingFang SC;
    font-weight: 400;
    letter-spacing: 0px;
  }
}

// :deep(.el-checkbox) {
//   height: 100%;
// }
</style>
